Skip to main content

Overview

The CustomTextCLIP class is a variant of the CLIP model that builds the text encoder as a separate module (self.text) rather than directly incorporating its components. This architecture provides:
  • Modularity: Easier to swap different text encoder architectures
  • Flexibility: Supports custom text encoders including HuggingFace models
  • Consistency: Parallel structure to the vision tower
  • Intermediate features: Better support for extracting text intermediate layer features
The main difference from standard CLIP is architectural organization, with identical training and inference capabilities.

Class Definition

Initialization Parameters

int
required
Dimensionality of the joint embedding space for image and text features.
CLIPVisionCfg
required
Configuration object for the vision encoder.
CLIPTextCfg
required
Configuration object for the text encoder. Supports both custom transformers and HuggingFace models via hf_model_name parameter.
bool
default:"False"
Use QuickGELU activation (as in original OpenAI models) instead of standard GELU.
float
default:"np.log(1 / 0.07)"
Initial value for the learned temperature parameter (logit scale).
Optional[float]
default:"None"
Optional learnable bias term added to logits. When None, no bias is used.
bool
default:"False"
If True, logit_scale has shape [1] instead of [].
Optional[torch.dtype]
default:"None"
Precision for model computations (e.g., torch.float16, torch.bfloat16).
bool
default:"False"
If True, forward() returns a dictionary with named outputs. If False, returns a tuple.

Attributes

  • visual: Vision encoder module (VisionTransformer, ModifiedResNet, or TimmModel)
  • text: Text encoder module (TextTransformer or HFTextEncoder)
  • logit_scale: Learned temperature parameter (exponential of stored value)
  • logit_bias: Optional learned bias (if init_logit_bias is not None)
  • context_length: Maximum text sequence length
  • vocab_size: Size of text vocabulary

Key Methods

encode_image

Encodes images into the joint embedding space. Parameters:
  • image: Image tensor of shape (batch_size, channels, height, width)
  • normalize: If True, L2-normalizes the output features
Returns: Image features of shape (batch_size, embed_dim)

encode_text

Encodes tokenized text into the joint embedding space. Parameters:
  • text: Tokenized text tensor of shape (batch_size, context_length)
  • normalize: If True, L2-normalizes the output features
Returns: Text features of shape (batch_size, embed_dim)

get_logits

Computes similarity logits between image and text features. Parameters:
  • image: Image tensor
  • text: Tokenized text tensor
Returns: Tuple of (image_logits, text_logits) representing similarity scores scaled by temperature

forward

Forward pass through the model. Parameters:
  • image: Optional image tensor
  • text: Optional tokenized text tensor
Returns:
  • If output_dict=True: Dictionary with keys image_features, text_features, logit_scale, and optionally logit_bias
  • If output_dict=False: Tuple of (image_features, text_features, logit_scale) or (image_features, text_features, logit_scale, logit_bias)

forward_intermediates

Forward pass that returns intermediate layer features from both vision and text encoders. This method provides better text intermediate support compared to standard CLIP. Returns: Dictionary with intermediate features, final features, and optionally logits

lock_image_tower

Freezes the image encoder for efficient fine-tuning. Parameters:
  • unlocked_groups: Number of layer groups to keep trainable (from the end)
  • freeze_bn_stats: If True, freezes batch normalization statistics

lock_text_tower

Freezes the text encoder for efficient fine-tuning. Delegates to the text module’s lock method. Parameters:
  • unlocked_layers: Number of transformer layers to keep trainable (from the end)
  • freeze_layer_norm: If True, freezes layer normalization parameters

set_grad_checkpointing

Enables or disables gradient checkpointing for both vision and text encoders to reduce memory usage.

Usage Example

Using HuggingFace Text Encoders

Extracting Intermediate Features

Selective Fine-tuning

Differences from Standard CLIP

Migration from CLIP

To convert existing CLIP state dictionaries to CustomTextCLIP format: